<?php
defined('IN_XLP') or exit('Access Denied');

class shopScoreModel extends Model {

	function __construct() {
		parent::__construct();
	}

	/**
	 * 检查用户积分是否够用
	 * @param  int $score 使用积分
	 * @return boolean
	 */
	public function checkUserScore($score, $uid) {

		if(!$uid || $score<0) return false;
		//用户总积分
		$result = M('user')->field('`shopping_credit`')->where(array('uid'=>$uid))->find();
		if(!$result) return false;

		$total_score = $result['shopping_credit'];

		$result = $total_score - $score;
		return $result>=0 ? true : false;
	}


	
	/**
	 * 更新用户积分
	 * @param int 	 $credit   积分数量
	 * @param int 	 $act      1：增加 0：减少
	 * @param string $order_sn 订单号
	 * @return int 			   1：成功 0：插入日志失败 -1：没有该用户 -2：积分不足
	 */
	public function setUserScore($credit, $act, $uid, $order_sn='', $prefix='') {

		$prefix = $prefix ? $prefix : '购物 订单号：';

        $data['uid']      = $uid;
        $data['act']	  = $act;
        $data['credit']	  = intval($credit);
        $data['content']  = $prefix.$order_sn;
		$data['infotime'] = TIME;

		if ($data['act']) {   //增加积分
			$result = M('user')->where(array('uid' => $data['uid']))->find();
			if(!$result) return -1;
			M('user')->where(array('uid' => $data['uid']))->setInc('shopping_credit', $data['credit']);
		} else {              //减少积分
			$result = $this->checkUserScore($data['credit'], $uid);
			if(!$result) return -2;
			M('user')->where(array('uid' => $data['uid']))->setDec('shopping_credit', $data['credit']);
		}

		//积分日志
		if (M('shopping_credit_log')->insert($data)) {
			return 1;
		} else {
			return 0;
		}

	}

}